package com.itheima.controller.backend.security;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.entity.Result2;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 检查组图片上传
 */
@RestController
@Slf4j
@RequestMapping("/setmeal/upload")
public class CommendController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 上传检查组图片
     * @param imgFile
     * @return
     */
    @PostMapping
    public Result2 upload(MultipartFile imgFile) {
        log.info("上传检查组图片"+ imgFile);

        try {
            String fileName = imgFile.getOriginalFilename();
            String substring = fileName.substring(fileName.lastIndexOf("."));
            String name = UUID.randomUUID().toString() + substring;
            String upload = aliOssUtil.upload(imgFile.getBytes(), name);
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES,upload);
            return new Result2(true, "上传检查组图片成功",upload);
        } catch (IOException e) {
           log.error("上传检查组图片失败",e);
        }

    return new Result2( false, "上传检查组图片失败");
}
}
